package com.openatc.agent.controller;

import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import com.openatc.agent.model.FaultRange;
import com.openatc.agent.model.WebOperationRecordRange;
import com.openatc.agent.resmodel.PageOR;
import com.openatc.agent.service.DevService;
import com.openatc.agent.service.HistoryDataDao;
import com.openatc.agent.service.impl.CommonService;
import com.openatc.core.common.IErrorEnumImplOuter;
import com.openatc.core.model.RESTRet;
import com.openatc.core.model.RESTRetBase;
import com.openatc.core.util.RESTRetUtils;
import com.openatc.model.model.AscsBaseModel;
import com.openatc.model.model.IntersectionStatisticsVo;
import com.openatc.model.model.PhasesStatisticsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author ：zhangwenchao
 * @date ：Created in 2021/10/18 17:39
 * @description：历史数据查询API
 * @modified By：
 * @version: $
 */

@RestController
@RequestMapping("/historydata")
public class HistoryDataController {

    @Autowired
    private HistoryDataDao historyDataDao;

    @Autowired
    private DevService devService;

    @Autowired
    private CommonService commService;
    /**
     * @return 历史方案记录
     * @Date 2021/9/1 9:49
     * @Descripation 查询指定agentId范围内的历史方案记录
     * 没有上传时间范围则查询1天的历史数据
     */
    @PostMapping(value = "/pattern/range")
    public RESTRetBase getPatternRange(@RequestBody JsonObject jsonObject) {
        String agentId = jsonObject.get("agentId").getAsString();
        String beginTime = jsonObject.get("beginTime").getAsString();
        String endTime = jsonObject.get("endTime").getAsString();
        return RESTRetUtils.successObj(historyDataDao.GetPatternData(agentId,beginTime,endTime));
    }

    @PostMapping(value = "/pattern/realtime/range")
    public RESTRetBase getPatternRealtimeRange(@RequestBody JsonObject jsonObject) {
        String agentId = jsonObject.get("agentId").getAsString();
        String beginTime = jsonObject.get("beginTime").getAsString();
        String endTime = jsonObject.get("endTime").getAsString();
        return RESTRetUtils.successObj(historyDataDao.GetPatternRealtimeData(agentId,beginTime,endTime));
    }

    /**
     * @return 历史流量记录
     * @Date 2021/9/1 9:49
     * @Descripation 查询指定agentId范围内的历史流量记录
     * 没有上传时间范围则查询1天的历史数据
     */
    @PostMapping(value = "/flow/range")
    public RESTRetBase getFlowRange(@RequestBody JsonObject jsonObject) {
        String agentId = jsonObject.get("agentId").getAsString();
        String beginTime = jsonObject.get("beginTime").getAsString();
        String endTime = jsonObject.get("endTime").getAsString();
        return RESTRetUtils.successObj(historyDataDao.GetFlowData(agentId,beginTime,endTime));
    }

    /**
     * 查询相位统计数据
     * @param jsonObject
     * @return
     */
    @PostMapping(value = "/phasesstatistics")
    public RESTRet getPhasesStatistics(@RequestBody JsonObject jsonObject){

        JsonElement beginTimeElement = jsonObject.get("beginTime");
        JsonElement endTimeElement = jsonObject.get("endTime");
        JsonElement phasenoElement = jsonObject.get("phaseno");
        JsonElement agentidElement = jsonObject.get("agentid");
        if (beginTimeElement == null || endTimeElement == null || phasenoElement == null || agentidElement == null){
            return RESTRetUtils.errorObj(false, IErrorEnumImplOuter.E_1000);
        }

        String beginTime = beginTimeElement.getAsString();
        String endTime = endTimeElement.getAsString();
        String agentid = agentidElement.getAsString();

        PhasesStatisticsVo phasesStatisticsVo;
        // 获取历史相位统计数据
        if ((!beginTime.isEmpty()) && (!endTime.isEmpty())) {
            phasesStatisticsVo = devService.getHistoryPhasesStatistics(agentid,jsonObject);
        }
        // 获取实时相位统计数据
        else {
            int phaseno = phasenoElement.getAsInt();
            phasesStatisticsVo = devService.getPhasesStatistics(agentid,phaseno);
        }
        return RESTRetUtils.successObj(phasesStatisticsVo);
    }

    @PostMapping(value = "/intesstatistics")
    public RESTRet getIntersectionStatistics(@RequestBody JsonObject jsonObject){
        JsonElement beginTimeElement = jsonObject.get("beginTime");
        JsonElement endTimeElement = jsonObject.get("endTime");
        JsonElement agentidElement = jsonObject.get("agentid");

        if (beginTimeElement == null || endTimeElement == null || agentidElement == null){
            return RESTRetUtils.errorObj(false,IErrorEnumImplOuter.E_1000);
        }
        String beginTime = beginTimeElement.getAsString();
        String endTime = endTimeElement.getAsString();
        String agentid = agentidElement.getAsString();

        IntersectionStatisticsVo vo;
        // 获取路口历史统计数据
        if ((!beginTime.isEmpty()) && (!endTime.isEmpty())) {
            vo = devService.getHistoryIntersectionStatistics(agentid,jsonObject);
        }
        // 获取路口实时统计数据
        else {
            vo = devService.getIntersectionStatistics(agentid);
        }

        return RESTRetUtils.successObj(vo);
    }

    /**
     * 获取路口基础统计数据
     * @param requestData
     * @return
     */
    @PostMapping(value = "/intbasedata/range")
    public RESTRetBase getIntBaseData(@RequestBody JsonObject requestData) {
        PageOR<AscsBaseModel> pageOR = new PageOR<>();

        // 分页条件
        int pageNum = requestData.get("pageNum").getAsInt() <= 1 ? 0 : requestData.get("pageNum").getAsInt() - 1;
        int pageRow = requestData.get("pageRow").getAsInt();
        String beginTime = "1970-01-01 00:00:00";
        String endTime = "2100-01-01 00:00:00";
        if (requestData.get("beginTime") != null) {
            beginTime = requestData.get("beginTime").getAsString();
        }
        if (requestData.get("endTime") != null) {
            endTime = requestData.get("endTime").getAsString();
        }

        String whereCondition = " where pattern_update_time between '" + beginTime + "' and '" + endTime + "' ";
        // 组织机构条件
        String orgCode = "";
        if (commService.hasOrgCondition(requestData)) {
            orgCode = requestData.get("code").getAsString();
        }
        String orgCondition = commService.buildOrgCondition(orgCode);
        whereCondition = commService.addWhereCondition(whereCondition, orgCondition);
        // 模糊查询条件
        String searchCondition = buildSearchCondition(requestData);
        whereCondition = commService.addWhereCondition(whereCondition,searchCondition);

        // 获取总数
        String countsql = "SELECT count(*) FROM dev ";
        countsql = countsql.concat(whereCondition);
        int count = historyDataDao.getDevCount(countsql);
        pageOR.setTotal((long) count);
        if(count == 0){ //没有查询记录直接返回
            return RESTRetUtils.successObj(pageOR);
        }

        String sql = "select id,status,agentid,name,code,phase_count,overlap_count,pattern_count,plan_count,date_count,veh_lamp_count,ped_lamp_count,pattern_update_time from dev";
        sql = sql.concat(whereCondition);
        sql = sql.concat(" ORDER BY id");
        String limitCondition = String.format(" limit  %d  offset  %d ",pageRow, pageNum*pageRow );
        sql = sql.concat(limitCondition);

        List<AscsBaseModel> devs = devService.getDevsBySql(sql);
        if (!CollectionUtils.isEmpty(devs)) {
//            pageOR.setTotal((long) devs.size());
            pageOR.setContent(devs);
        }
        return RESTRetUtils.successObj(pageOR);
    }

    private String buildSearchCondition(JsonObject requestData) {
        String temp = "";
        // 模糊条件
        if (commService.hasSearchCondition(requestData)) {
            String search = requestData.get("search").getAsString();
            if (StringUtils.hasLength(search)) {
                temp = String.format("name like '%%%s%%'",search);
            }
        }
        return temp;
    }


    /**
     * 获取路口操作频次数据
     * @param requestData
     * @return
     */
    @PostMapping(value = "/operation/frequency")
    public RESTRetBase getOperationFrequency(@RequestBody JsonObject requestData) {
        // 参数校验
        try {
            commService.verifyParam(requestData,"agentid","startTime","endTime","type","intervalType");
        } catch (IllegalArgumentException e) {
            return RESTRetUtils.errorObj("9999",e.getMessage(),"/historydata/operation/frequency",null);
        }

        String agentid = requestData.get("agentid").getAsString();
        String startTime = requestData.get("startTime").getAsString();
        String endTime = requestData.get("endTime").getAsString();
        int type = requestData.get("type").getAsInt();
        String intervalType = requestData.get("intervalType").getAsString();

        JsonArray frequencyData = historyDataDao.getIntOperationCount(agentid,startTime,endTime,type,intervalType);

        int totalCount = 0;
        for (JsonElement data : frequencyData) {
            int count = data.getAsJsonObject().get("count").getAsInt();
            totalCount+=count;
        }

        JsonObject resData = new JsonObject();
        resData.addProperty("agentid",agentid);
        resData.addProperty("type",type);
        resData.addProperty("total",totalCount);
        resData.add("data",frequencyData);
        return RESTRetUtils.successObj(resData);
    }

    /**
     * 获取历史方案数据
     * @param requestData
     * @return
     */
    @PostMapping("/cycle")
    public RESTRetBase getCycleHisData(@RequestBody JsonObject requestData) {
        // 参数校验
        try {
            commService.verifyParam(requestData,"agentid","startTime","endTime");
        } catch (IllegalArgumentException e) {
            return RESTRetUtils.errorObj("9999",e.getMessage(),"/historydata/cycle",null);
        }

        Gson gson = new GsonBuilder().create();

        String agentid = requestData.get("agentid").getAsString();
        String startTime = requestData.get("startTime").getAsString();
        String endTime = requestData.get("endTime").getAsString();
        int interval = requestData.get("interval").getAsInt();
        JsonElement weekEle = requestData.get("weeks");
        List<Integer> weeks = null;
        if (weekEle != null) {
            weeks = gson.fromJson(weekEle.getAsJsonArray(),new TypeToken<List<Integer>>(){}.getType());
        }


        JsonArray cycleData = historyDataDao.getCycleHisData(agentid,startTime,endTime,interval,weeks);

        return RESTRetUtils.successObj(cycleData);
    }

    /**
     * 获取平台操作记录统计
     * @param requestData
     * @return
     */
    @PostMapping("/operation/platform")
    public RESTRetBase getPlatFormOperation(@RequestBody WebOperationRecordRange requestData) {
        JsonArray operationData = historyDataDao.getPlatFormOperation(requestData);
        return RESTRetUtils.successObj(operationData);
    }

    /**
     * 获取故障统计记录
     * @param requestData
     * @return
     */
    @PostMapping("/fault")
    public RESTRetBase getFaultStatistics(@RequestBody FaultRange requestData) {
        JsonArray faultData = historyDataDao.getFaultStatistics(requestData);
        return RESTRetUtils.successObj(faultData);
    }

}
